<?php
class Sprint_Model extends CI_Model{
    function _construct(){
		parent::_construct();
	}
	
	function getSprints($sidx, $sord, $start , $limit) {
		$this->db->order_by($sidx, $sord);
		$this->db->limit($limit, $start);
		$this->db->select('id, start_date, end_date, status');
		$query = $this->db->get('sprints');
		return $query->result_array(); 
	}
	
	function getSprintsCount() {
		return $this->db->count_all_results('sprints');
	}
	function controlInProgress($status,$idSprint){
		if($status=='In Progress'){
			$query=$this->db->get_where('sprints', array('status' => "In Progress", "id <>" => $idSprint ));
			if($query->num_rows()>0){
				return true;
			}
		}
		return false;
	}
	function create($start_date, $end_date, $name, $status,$project_id){
		$data = array(
       		'start_date' => $start_date ,
       		'end_date' 	 => $end_date , 
			'name'		 => $name,
			'status' 	 => $status,
			'project_id' => $project_id 
       );  
	   $this->db->insert('sprints', $data);
	   return  $this->db->insert_id();
    }
 	function delete ($sprint){
    	$this->db->delete('sprints', array('id' => $sprint)); 
    }
    function update($id,$start_date,$end_date, $name, $status){    		
    	$data = array(
        	'start_date'=> $start_date ,
       		'end_date' 	=> $end_date ,
    		'name'		=> $name, 
			'status' 	=> $status 
        );
		$this->db->where('id', $id);
		$this->db->update('sprints', $data);
    } 
    
    public function get_project_sprints($project_id){
		$this->db->select('id, start_date, end_date');
		$query = $this->db->get_where('sprints', array('project_id' => $project_id));
		return $query->result_array();
    }
    
	function get_like_sprints($term) {
		$this->db->like('name', $term, 'after');
		$this->db->select('id, name');
		$query = $this->db->get('sprints');
		return $query->result_array();  
	}
	
	function get($id){
    	$query=$this->db->get_where('sprints', array('id' => $id));
     	return $query->result_array();
    }
    
	/**
	* Gets sprint with status In Progress
	* @return $c_sprint - current sprint
	*/
	public function get_current_sprint(){
		$project_id = $this->session->userdata('current_project');
		$c_sprint 	= null;
		
		$this->db->where('project_id', $project_id);
		$this->db->where('status', 'In Progress');
		$query = $this->db->get('sprints');
		
		$sprints = $query->result_array();
		
		if($sprints != null){
			$c_sprint = $sprints[0];
		}
		return $c_sprint;
	}
}
